<template>
	<view class="cart-container">

		<!-- 购物车有商品时 -->
		<view v-if="cartItems.length > 0" class="cart-content">
			<!-- 商品列表 -->
			<view class="cart-list">
				<view class="cart-item" v-for="(item, index) in cartItems" :key="item.id">
					<!-- 右上角删除按钮 -->
					<view class="item-delete-x" @click="removeItem(index)">
						<text class="delete-x-text">✕</text>
					</view>
					
					<view class="item-select">
						<checkbox :checked="item.selected" @click="toggleItemSelect(index)"></checkbox>
					</view>
					<view class="item-image">
						<image :src="item.image" mode="aspectFill"></image>
					</view>
					<view class="item-info">
						<text class="item-name">{{ item.name }}</text>
						<text class="item-spec">{{ item.specification }}</text>
						<view class="item-price-quantity">
							<text class="item-price">¥{{ item.price }}</text>
							<view class="quantity-control">
								<button class="quantity-btn" @click="decreaseQuantity(index)">-</button>
								<text class="quantity-text">{{ item.quantity }}</text>
								<button class="quantity-btn" @click="increaseQuantity(index)">+</button>
							</view>
						</view>
					</view>
				</view>
			</view>


		</view>

		<!-- 购物车为空时 -->
		<view v-else class="empty-cart">
			<image :src="pageImages.cart_empty_image" class="empty-image"></image>
			<text class="empty-text">购物车还是空的</text>
			<text class="empty-tip">快去挑选心仪的珠宝吧</text>
			<button class="go-shopping-btn" @click="goShopping">去逛逛</button>
		</view>

		<!-- 底部结算栏 -->
		<view v-if="cartItems.length > 0" class="checkout-bar">
			<view class="select-all">
				<checkbox :checked="isAllSelected" @click="toggleSelectAll"></checkbox>
				<text class="select-all-text">全选</text>
			</view>
			<view class="total-info">
				<text class="total-text">合计：</text>
				<text class="total-price">¥{{ totalPrice }}</text>
			</view>
			<button class="checkout-btn" :disabled="selectedItems.length === 0" @click="goCheckout">
				结算({{ selectedItems.length }})
			</button>
		</view>
	</view>
</template>

<script>
import CartManager from '@/utils/cart.js'
import { getPageImages } from '@/utils/imageConfig.js'

export default {
	data() {
		return {
			// 页面图片配置
			pageImages: {
				cart_delete_icon: '/static/icons/delete.png',
				cart_empty_image: '/static/images/empty-cart.png'
			},
			// 购物车商品列表
			cartItems: []
		}
	},
	computed: {
		// 已选中的商品
		selectedItems() {
			return this.cartItems.filter(item => item.selected);
		},

		// 是否全选
		isAllSelected() {
			return this.cartItems.length > 0 && this.cartItems.every(item => item.selected);
		},

		// 总价格
		totalPrice() {
			return this.selectedItems.reduce((total, item) => {
				return total + (item.price * item.quantity);
			}, 0).toFixed(2);
		}
	},
	async onLoad() {
		await this.loadPageImages();
		this.loadCartData();
	},
	onShow() {
		// 页面显示时刷新购物车数据
		this.refreshCartData();
	},
	methods: {
		// 加载页面图片配置
		async loadPageImages() {
			try {
				const images = await getPageImages('cart');

				if (images.cart_delete_icon) {
					this.pageImages.cart_delete_icon = images.cart_delete_icon.url;
				}
				if (images.cart_empty_image) {
					this.pageImages.cart_empty_image = images.cart_empty_image.url;
				}

				console.log('购物车页面图片配置加载完成');
			} catch (error) {
				console.warn('加载页面图片配置失败，使用默认图片:', error);
			}
		},

		// 加载购物车数据
		loadCartData() {
			this.cartItems = CartManager.getCartItems();
		},

		// 刷新购物车数据
		refreshCartData() {
			this.cartItems = CartManager.getCartItems();
		},



		// 切换商品选中状态
		toggleItemSelect(index) {
			const item = this.cartItems[index];
			if (CartManager.toggleItemSelect(item.id)) {
				this.refreshCartData();
			}
		},

		// 全选/取消全选
		toggleSelectAll() {
			const selectAll = !this.isAllSelected;
			if (CartManager.toggleSelectAll(selectAll)) {
				this.refreshCartData();
			}
		},

		// 增加商品数量
		increaseQuantity(index) {
			const item = this.cartItems[index];
			if (CartManager.updateQuantity(item.id, item.quantity + 1)) {
				this.refreshCartData();
			}
		},

		// 减少商品数量
		decreaseQuantity(index) {
			const item = this.cartItems[index];
			if (item.quantity > 1) {
				if (CartManager.updateQuantity(item.id, item.quantity - 1)) {
					this.refreshCartData();
				}
			}
		},

		// 移除商品
		removeItem(index) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这件商品吗？',
				success: (res) => {
					if (res.confirm) {
						const item = this.cartItems[index];
						if (CartManager.removeFromCart(item.id)) {
							this.refreshCartData();
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					}
				}
			});
		},




		// 去购物
		goShopping() {
			uni.switchTab({
				url: '/pages/category/category'
			});
		},

		// 去结算 -> 跳转到订单确认页面
		goCheckout() {
			if (this.selectedItems.length === 0) {
				uni.showToast({
					title: '请选择要结算的商品',
					icon: 'none'
				});
				return;
			}

			// 将选中的商品信息传递给订单确认页面
			const orderData = {
				items: this.selectedItems.map(item => ({
					product_id: item.id,
					product_name: item.name,
					product_image_url: item.image,
					price: item.price,
					quantity: item.quantity
				})),
				total_amount: Number(this.totalPrice)
			};

			// 跳转到订单确认页面
			uni.navigateTo({
				url: `/pages/order/confirm?data=${encodeURIComponent(JSON.stringify(orderData))}`
			});
		},

		// 清空购物车
		clearCart() {
			uni.showModal({
				title: '确认清空',
				content: '确定要清空购物车吗？',
				success: (res) => {
					if (res.confirm) {
						if (CartManager.clearCart()) {
							this.refreshCartData();
							uni.showToast({
								title: '购物车已清空',
								icon: 'success'
							});
						}
					}
				}
			});
		}
	}
}
</script>

<style scoped>
.cart-container {
	background-color: #F5F5F5;
	min-height: 100vh;
	/* 留出底部 tabBar 与安全区以及结算栏的空间，避免被遮挡 */
	padding-bottom: calc(140rpx + var(--window-bottom) + env(safe-area-inset-bottom));
}

/* 购物车商品列表 */
.cart-list {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	overflow: hidden;
}

.cart-item {
	position: relative;
	display: flex;
	align-items: center;
	padding: 30rpx 20rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.cart-item:last-child {
	border-bottom: none;
}

/* 右上角删除按钮 */
.item-delete-x {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	background-color: #FF4444;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 10;
}

.delete-x-text {
	color: #FFFFFF;
	font-size: 24rpx;
	font-weight: bold;
	line-height: 1;
}

.item-select {
	margin-right: 20rpx;
}

.item-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 12rpx;
	overflow: hidden;
	margin-right: 20rpx;
}

.item-image image {
	width: 100%;
	height: 100%;
}

.item-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	height: 160rpx;
}

.item-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 10rpx;
}

.item-spec {
	font-size: 24rpx;
	color: #999999;
	margin-bottom: 20rpx;
}

.item-price-quantity {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.item-price {
	font-size: 32rpx;
	color: #D4AF37;
	font-weight: bold;
}

.quantity-control {
	display: flex;
	align-items: center;
	border: 1rpx solid #E0E0E0;
	border-radius: 20rpx;
	overflow: hidden;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	background-color: #F5F5F5;
	border: none;
	font-size: 32rpx;
	color: #666666;
	display: flex;
	align-items: center;
	justify-content: center;
}

.quantity-text {
	width: 80rpx;
	text-align: center;
	font-size: 28rpx;
	color: #333333;
}


/* 空购物车样式 */
.empty-cart {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 200rpx 40rpx;
	text-align: center;
}

.empty-image {
	width: 300rpx;
	height: 300rpx;
	margin-bottom: 40rpx;
	opacity: 0.6;
}




.empty-text {
	font-size: 36rpx;
	color: #333333;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.empty-tip {
	font-size: 28rpx;
	color: #999999;
	margin-bottom: 60rpx;
}

.go-shopping-btn {
	background-color: #D4AF37;
	color: #FFFFFF;
	border: none;
	border-radius: 50rpx;
	padding: 30rpx 80rpx;
	font-size: 32rpx;
	font-weight: bold;
}

/* 底部结算栏 */
.checkout-bar {
	position: fixed;
	/* 与底部 tabBar 错开，防止重叠 */
	bottom: var(--window-bottom);
	left: 0;
	right: 0;
	z-index: 1000;
	background-color: #FFFFFF;
	border-top: 1rpx solid #E0E0E0;
	padding: 20rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.select-all {
	display: flex;
	align-items: center;
}

.select-all-text {
	font-size: 28rpx;
	color: #333333;
	margin-left: 10rpx;
}

.total-info {
	flex: 1;
	text-align: center;
}

.total-text {
	font-size: 28rpx;
	color: #333333;
}

.total-price {
	font-size: 36rpx;
	color: #D4AF37;
	font-weight: bold;
}

.checkout-btn {
	background-color: #D4AF37;
	color: #FFFFFF;
	border: none;
	border-radius: 50rpx;
	padding: 25rpx 50rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.checkout-btn[disabled] {
	background-color: #CCCCCC;
	color: #999999;
}
</style>
